import re
import autoconf_depends
import pprint

def parse_configure_options(file_path):
    with open(file_path, 'r', encoding='utf-8', errors='ignore') as file:
        configure_content = file.read()

    options_dict = {}
    match = re.search(r'Optional Features:(.*?)(?=Some influential environment variables:)', configure_content, re.DOTALL)
    sections = match.group(1).strip() if match else ''

    sections = re.sub(r'Optional Features:', '', sections)
    sections = re.sub(r'Optional Packages:', '', sections)

    if sections == '':
        return
    
    print(sections)
    lines = sections.splitlines()
    current_key = None
    current_help = []
    # special_flag = False
    
    for line in lines:
        line = line.strip()
        if line:
            # 检查是否是新的选项行
            match = re.match(r'(--(?:enable|disable|with|without)-[\w_-]+)(\[=\w+\])?(.*)', line)
            
            if match:
                for i in range(1, match.lastindex + 1):
                    print(f"Group {i}: {match.group(i)}")
                # 如果当前已有 key，先保存
                if current_key:
                    options_dict[current_key]['help'] = ' '.join(current_help).strip()
                
                # 处理新的选项
                argv = match.group(1).strip()
                key = argv.replace('--enable-', '').replace('--disable-', '').replace('--with-', '').replace('--without-', '')
                # if key == 'PACKAGE' or key == 'FEATURE':
                #     current_key = None
                #     continue

                # clean_key = re.sub(r'[^a-zA-Z_-]', '', key)
                # print(f'clean_key:{clean_key}')
                
                # current_key = clean_key
                current_key = key
                options_dict[current_key] = {'argv': argv}

                # 处理 help 文本
                current_help = [match.group(3).strip()]
                print(f"current_help:{current_help}")
                
                # 处理 default 值
                default_match = re.search(r'\[default=(yes|no)', line)

                if default_match:
                    if default_match.group(1) == 'yes':
                        options_dict[current_key]['default'] = True
                    elif default_match.group(1) == 'no':
                        options_dict[current_key]['default'] = False
                
                options_dict[current_key]['name'] = current_key
            else:
                current_help.append(line)
        else:
            # 处理空行：如果遇到空行且有当前键，则保存当前选项
            if current_key:
                options_dict[current_key]['help'] = ' '.join(current_help).strip()
    # 添加最后一个选项
    if current_key:
        options_dict[current_key]['help'] = ' '.join(current_help).strip()
        options_dict[current_key]['name'] = current_key

    return options_dict
    

    # sections = re.split(r'\n\s*\n', configure_content.strip())
    # options_dict = {}

    # for section in sections:
    #     if section.startswith("Optional Features:") or section.startswith("Optional Packages:"):
    #         lines = section.splitlines()[1:]  # 跳过标题行
    #         for line in lines:
    #             line = line.strip()
    #             if line:
    #                 # 使用正则表达式提取 argv 和 help
    #                 match = re.match(r'(--\w+)(.*)', line)
    #                 if match:
    #                     argv = match.group(1).strip()
    #                     help_text = match.group(2).strip()
                        
    #                     # 处理前缀和符号
    #                     key = argv.replace('--', '').replace('with-', 'with_').replace('without-', 'without_').replace('enable-', 'enable_').replace('disable-', 'disable_')
    #                     key = key.replace('-', '_')

    #                     # 构造字典
    #                     options_dict[key] = {
    #                         'name': key,
    #                         'set_var': [f"{key}=yes"],
    #                         'argv': argv,
    #                         'help': help_text
    #                     }

    # return options_dict



# auto_depends = autoconf_depends.AutoconfDepends()

file_path = '/home/elpsy/workspace/sow/dependency-analysis/configure'

option_dict = parse_configure_options(file_path)
pprint.pprint(option_dict)